<?php

namespace App\Http\Controllers;


use App\Models\Budget;
use App\Models\Expenses;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class Accounting extends Controller
{
    // 首页功能

    // 获取首页的数据 1.当月日期 2.当月预算 3.当月总支出 4.当月支出/预算比例 5.获取最新的三条消费记录 按照天来排序
    public function getIndexInfo(Request $request): JsonResponse
    {
        $user_id = $request->input('token_uid');
        //返回数据准备
        $info = [
//            'date' => '',
//            'budget' => 0,
//            'expenses_sum' => '',
//            'expenses_budget' => '',
//            'expenses' => [],
        ];
        //获取当日日期
        $now_time = time();
        $info['date'] = date('Y-m-d', $now_time);
        $year = date('Y');
        $month = date('m');
        //获取当月预算
        $info['budget'] = Budget::getBudgeByYearMonth($year, $month, $user_id);
        //获取当月总支出
        $info['expenses_sum'] = Expenses::getSumExpensesByYearMonth($year, $month, $user_id);
        $info['expenses_sum'] = format_money($info['expenses_sum']);
        //获取预算和支出百分比88.55保留两位小数
        if ($info['budget'] == 0) {
            $info['budget'] = '暂无';
            $info['expenses_budget'] = 0;
        } else {
            // 格式化金额数据
            $info['budget'] = format_money($info['budget']);
            $info['expenses_budget'] = round($info['expenses_sum'] / $info['budget'], 4) * 100 . '%';
        }
        //获取最新的三条数据并处理成按照天数的数组
        $limit_list = Expenses::getLastExpensesByYearMonth($year, $month, $user_id);
        $info['expenses'] = Expenses::dealExpensesListGroupByDay($limit_list);
        # 返回
        return response()->json(create_response_data('成功', true, $info));
    }

    // 获取某年某月的预算
    public function getBudgetByYearMonth(Request $request): JsonResponse
    {
        $user_id = $request->input('token_uid');
        $input = $request->only(['year', 'month']);
//        # 验证数据
//        $validator = Validator::make(
//            $input,
//            [
//                'year' => ['numeric', 'required'],
//                'month' => ['numeric', 'required']
//            ],
//            [
//                'account' => '年份需要填写数字',
//                'password' => '月份需要填写数字'
//            ],
//        );
//        # 验证失败直接返回
//        if ($validator->fails()) {
//            $errors = $validator->errors();
//            return response()->json(create_response_data($errors->first(), false));
//        }
        $budget = Budget::getBudgeByYearMonth($input['year'], $input['month'], $user_id);
        # 返回
        return response()->json(create_response_data('成功', true, ['budget' => $budget]));
    }

    // 修改某月预算
    public function alterBudgetByMonthYear(Request $request): JsonResponse
    {
        $input = $request->only(['year', 'month', 'money']);
        $user_id = $request->input('token_uid');
        $rs = Budget::setBudgeByYearMonth($input['year'], $input['month'], $input['money'], $user_id);
        # 返回
        return response()->json(create_response_data($rs ? '成功' : '失败', $rs));
    }

    // 获取支出分类
    public function getExpensesType(): JsonResponse
    {
        $list = Expenses::$types;
        return response()->json(create_response_data('成功', true, $list));
    }

    // 新增支出
    public function addExpenses(Request $request): JsonResponse
    {
        $user_id = $request->input('token_uid');
        $input = $request->only('money', 'date', 'type', 'title', 'content');
        $types = Expenses::$types;
        //        # 验证数据
        $validator = Validator::make(
            $input,
            [
                'money' => ['numeric', 'required'],
                'date' => ['date', 'required'],
                'type' => [
                    'required',
                    Rule::in($types),
                ],
                'title' => ['string', 'required', 'max:10'],
                'content' => ['string', 'max:30'],
            ],
            [
                'money' => '请填写正确金额',
                'date' => '请选择日期',
                'type' => '类别错误',
                'title.required' => '消费标题必须填写',
                'title.max' => '消费标题需要小于10个字符',
                'content'=> '内容需要小于20个字符',
            ],
        );
        // 验证失败直接返回
        if ($validator->fails()) {
            $errors = $validator->errors();
            return response()->json(create_response_data($errors->first(), false));
        }
        // 拆分date
        $date_split = explode(',', $input('date'));
        $year = $date_split[0];
        $month = $date_split[1];
        $day = $date_split[2];
        $res = Expenses::addExpenses($input['money'], $year, $month, $day, $input['type'], $user_id, $input['title'], $input['content']);
        return response()->json(create_response_data($res ? '成功' : '写入失败', $res));
    }

    // 删除支出
    public function delExpenses(Request $request): JsonResponse
    {
        $id = $request->input('id');
        $user_id = $request->input('user_id');
        $res = Expenses::deleteExpenses($id, $user_id);
        return response()->json(create_response_data($res ? '成功' : '失败', (bool)$res));
    }

    // 获取存在支出的月份(仅获取近两年)
    public function getHaveExpenseMonth(Request $request): JsonResponse
    {
        $user_id = $request->input('token_uid');
        $year = (int)date('Y');
        $start_year = $year - 1;
        $res = Expenses::getHaveExpenseMonth($start_year, $year, $user_id);
        return response()->json(create_response_data('成功', true, $res));
    }

    // 根据年月获取历史数据 1.当月预算 2.当月支出总额 3.日平均花销 4.历史列表（按照天给）
    public function getHistoryInfoByYearMonth(Request $request): JsonResponse
    {
        $data = [
//            'budget' => 0,
//            'expenses' => 0,
//            'avg' => 0,
//            'history' => []
        ];
        $user_id = $request->input('token_uid');
        $year = (int)$request->input('year');
        $month = (int)$request->input('month');
        // 当月预算
        $data['budget'] = Budget::getBudgeByYearMonth($year, $month, $user_id);
        // 当月总支出
        $data['expenses'] = Expenses::getSumExpensesByYearMonth($year, $month, $user_id);
        // 计算日平均花销
        $data['avg'] = Expenses::calculateMonthAvgExpenses($year, $month, $data['expenses']);
        // 获取历史数据
        $list = Expenses::getExpensesByYearMonth($year, $month, $user_id);
        //格式化一下历史数据
        $data['history'] = Expenses::dealExpensesListGroupByDay($list);
        //格式化一下金额数据
        $data['budget'] = format_money($data['budget']);
        $data['expenses'] = format_money($data['budget']);
        $data['avg'] = format_money($data['avg']);
        return response()->json(create_response_data('成功', true, $data));
    }


    // 获取有支出数据的年份
    public function getHaveExpenseYear(Request $request): JsonResponse
    {
        $user_id = $request->input('token_uid');
        $list = Expenses::getHaveExpenseYear($user_id);
        if (empty($list)) {
            //没有的话就给一个今年
            $list = [date('Y')];
        }
        return response()->json(create_response_data('成功', true, $list));
    }

    // 根据年份获取每月支出信息 1.年支出总额 2.每月支出总额
    public function getMonthExpensesByYear(Request $request): JsonResponse
    {
        $user_id = $request->input('token_uid');
        $year = $request->input('year');
        $expenses = Expenses::getSumExpensesByYear($year, $user_id);
        $month_expenses = Expenses::getMonthGroupExpensesByYear($year, $user_id);
        $data = [
            'expenses' => format_money($expenses),
            'month_expenses' => $month_expenses,
        ];
        return response()->json(create_response_data('成功', true, $data));
    }

    // 根据月获取支出信息 1.月支出总额 2.月平均支出 3.分类支出占比和金额
    public function getMonthExpensesDetail(Request $request): JsonResponse
    {
        $user_id = $request->input('token_uid');
        $year = $request->input('year');
        $month = $request->input('month');
        // 支出总额
        $expenses = Expenses::getSumExpensesByYearMonth($year, $month, $user_id);
        // 日平均支出
        $avg = Expenses::calculateMonthAvgExpenses($year, $month, $expenses);
        // 分类占比和金额
        $rate = Expenses::getMonthExpensesTypeRate($year, $month, $user_id, $expenses);
        $data = [
            'expenses' => format_money($expenses),
            'avg' => format_money($expenses),
            'rate' => $rate
        ];
        return response()->json(create_response_data('成功', true, $data));
    }
}
